// 业务逻辑中使用

const passport = require('../util/passport')
const userDao = require('../service/user_dao')
const md5 = require('../util/md5solt')
const uuid = require('node-uuid')

module.exports = {

  //登录跳转
  login: async (ctx, next) => {
    await ctx.render('login', {
      error: ''
    })
  },

  // 登录逻辑
  checklogin: async (ctx, next) => {
    return passport.authenticate('local', async (err, user, info) => {
      if (err) {
        await ctx.render('error', {
          message: '抱歉，权限验证错误！',
          error: err
        });
      }
      if (!user) {
        await ctx.render('login', {
          error: info
        })
      } else {
        ctx.login(user)
        await ctx.response.redirect('/index')
      }
    })(ctx);

  },

  // 欢迎页面跳转
  welcome: async (ctx, next) => {
    await ctx.render('welcome', {
      error: ''
    })
  },

  // 主页跳转
  index: async (ctx, next) => {
    let userInfo = {
      user_id: ctx.session.userId,
      user_name: ctx.session.userName
    };
    if (!ctx.isAuthenticated()) { //判断是否认证
      await ctx.render('login', {
        error: '请重新登陆'
      })
    } else {
      let userInfo = ctx.state.user //认证用户
      await ctx.render('index', {
        userInfo: userInfo
      })
    }
  },

  // 退出登录
  logout: async (ctx, next) => {
    ctx.logout()
    await ctx.render('login', {
      error: ''
    })
  },

  // 注册逻辑
  register: async (ctx, next) => {
    let body = ctx.request.body
    var solt = uuid.v4();
    var password = body.password;
    var md5Pass = await md5.MD5(password, solt);
    body.solt = solt;
    body.password = md5Pass;
    console.log(body);
    userDao.createUser(body)
    await ctx.redirect('/index', {
      result: true
    })
  }
}